﻿using System;
using System.Web;
using System.Web.Mvc;
using Orchard.Mvc.Filters;
using Orchard.UI.Admin;
using Orchard.UI.Resources;
using Orchard.Utility.Extensions;
using SuperClassic.Services;

namespace SuperClassic.Filters {
    public class TrackerFilter : FilterProvider, IResultFilter {
        private readonly ISettingsService _settingsService;
        private readonly IResourceManager _resourceManager;

        public TrackerFilter(
            ISettingsService settingsService,
            IResourceManager resourceManager) {
            _settingsService = settingsService;
            _resourceManager = resourceManager;
        }

        public void OnResultExecuting(ResultExecutingContext filterContext) {
            // ignore tracker on admin pages
            if (AdminFilter.IsApplied(filterContext.RequestContext)) {
                return;
            }

            // should only run on a full view rendering result
            if (!(filterContext.Result is ViewResult))
                return;

            var settings = _settingsService.GetSettings();

            if(String.IsNullOrEmpty(settings.AlternateCss)) {
                return;
            }

            // including the font-family in the query enables client caching
            _resourceManager.Include("stylesheet", "~/Themes/SuperClassic/Styles/Site.css?f=" + HttpUtility.UrlEncode(settings.FontFamily.HtmlClassify()), null, null);
            _resourceManager.Include("stylesheet", settings.AlternateCss, null, null);

        }

        public void OnResultExecuted(ResultExecutedContext filterContext) {
        }
    }
}